package com.xb.system.controller;

import com.xb.model.domain.entity.PaymentOrder;
import com.xb.system.common.result.Result;
import com.xb.system.service.PaymentService;
import com.xb.system.utils.UserContext;
import com.xb.system.utils.XMLUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    /**
     * 创建支付订单
     * @param params 订单参数
     * @return 结果
     */
    @PostMapping("/createOrder")
    public Result<Object> createOrder(@RequestBody Map<String, Object> params) {
        try {
            // 优先从前端传递的参数中获取userId，如果没有则从UserContext获取，都没有则为null（匿名用户）
            Long userId = null;
            if (params.containsKey("userId") && params.get("userId") != null) {
                try {
                    userId = Long.parseLong(params.get("userId").toString());
                } catch (Exception e) {
                    log.warn("前端传递的userId格式错误: {}", params.get("userId"));
                }
            }
            
            // 如果前端没有传递userId，尝试从UserContext获取
            if (userId == null) {
                userId = UserContext.getUserId();
            }
            
            // 如果还是没有userId，设置为null（匿名用户，后端会处理为0）
            log.info("创建订单，userId来源: 前端传递={}, UserContext={}, 最终userId={}", 
                    params.get("userId"), UserContext.getUserId(), userId);
            
            BigDecimal amount = new BigDecimal(params.get("amount").toString());
            Integer paymentType = Integer.parseInt(params.get("paymentType").toString());
            String packageType = (String) params.get("packageType");
            Integer packagePoints = Integer.parseInt(params.get("packagePoints").toString());
            String packageDuration = (String) params.get("packageDuration");
            
            // 检查是否为19.9套餐，如果是则验证用户是否已购买过（需要userId）
            if (userId != null && amount.compareTo(new BigDecimal("19.9")) == 0) {
                boolean hasPurchased = paymentService.hasUserPurchasedSpecialPackage(userId);
                if (hasPurchased) {
                    return Result.fail("您已购买过该体验套餐，每个用户仅限购买一次");
                }
            }
            
            PaymentOrder order = paymentService.createPaymentOrder(
                userId, amount, paymentType, packageType, packagePoints, packageDuration
            );
            
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("orderNo", order.getOrderNo());
            resultMap.put("amount", order.getAmount());
            resultMap.put("qrCodeUrl", order.getQrCodeUrl());
            resultMap.put("paymentType", order.getPaymentType());
            
            return Result.ok(resultMap);
        } catch (Exception e) {
            log.error("创建支付订单异常", e);
            return Result.fail("创建支付订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询订单状态
     * @param orderNo 订单号
     * @return 结果
     */
    @GetMapping("/orderStatus/{orderNo}")
    public Result<Object> queryOrderStatus(@PathVariable("orderNo") String orderNo) {
        try {
            PaymentOrder order = paymentService.queryPaymentOrder(orderNo);
            if (order == null) {
                return Result.fail("订单不存在");
            }
            
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("orderNo", order.getOrderNo());
            resultMap.put("status", order.getStatus());
            resultMap.put("amount", order.getAmount());
            resultMap.put("createTime", order.getCreateTime());
            
            if (order.getStatus() == 1) {
                resultMap.put("payTime", order.getPayTime());
                resultMap.put("transactionId", order.getTransactionId());
            }
            
            return Result.ok(resultMap);
        } catch (Exception e) {
            log.error("查询订单状态异常", e);
            return Result.fail("查询订单状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消订单
     * @param orderNo 订单号
     * @return 结果
     */
    @PostMapping("/cancelOrder/{orderNo}")
    public Result<Object> cancelOrder(@PathVariable("orderNo") String orderNo) {
        try {
            boolean success = paymentService.cancelPaymentOrder(orderNo);
            if (success) {
                return Result.ok();
            } else {
                return Result.fail("取消订单失败");
            }
        } catch (Exception e) {
            log.error("取消订单异常", e);
            return Result.fail("取消订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户支付记录
     * @return 结果
     */
    @GetMapping("/records")
    public Result<Object> getPaymentRecords() {
        try {
            Long userId = UserContext.getUserId();
            List<PaymentOrder> records = paymentService.getUserPaymentRecords(userId);
            return Result.ok(records);
        } catch (Exception e) {
            log.error("获取支付记录异常", e);
            return Result.fail("获取支付记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查用户是否已购买19.9套餐
     * @return 结果
     */
    @GetMapping("/checkSpecialPackage")
    public Result<Object> checkSpecialPackage() {
        try {
            Long userId = UserContext.getUserId();
            boolean hasPurchased = paymentService.hasUserPurchasedSpecialPackage(userId);
            
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("hasPurchased", hasPurchased);
            
            return Result.ok(resultMap);
        } catch (Exception e) {
            log.error("检查特殊套餐购买状态异常", e);
            return Result.fail("检查失败: " + e.getMessage());
        }
    }
    
    /**
     * 微信支付回调接口
     * @param request 请求
     * @return 结果
     */
    @PostMapping("/wechatNotify")
    public String wechatNotify(HttpServletRequest request) {
        try {
            // 从请求中读取XML数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            
            String xmlData = sb.toString();
            log.info("接收到微信支付回调XML数据: {}", xmlData);
            
            // 将XML转换为Map
            Map<String, String> notifyData = XMLUtil.xmlToMap(xmlData);
            
            boolean success = paymentService.handleWechatPayNotify(notifyData);
            if (success) {
                return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            } else {
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>";
            }
        } catch (Exception e) {
            log.error("处理微信回调异常", e);
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理异常]]></return_msg></xml>";
        }
    }
    
    /**
     * 支付宝支付回调接口
     * @param request 请求
     * @return 结果
     */
    @PostMapping("/alipayNotify")
    public String alipayNotify(HttpServletRequest request) {
        try {
            // 解析支付宝回调参数
            Map<String, String> notifyData = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                notifyData.put(entry.getKey(), entry.getValue()[0]);
            }
            
            boolean success = paymentService.handleAlipayNotify(notifyData);
            if (success) {
                return "success";
            } else {
                return "fail";
            }
        } catch (Exception e) {
            log.error("处理支付宝回调异常", e);
            return "fail";
        }
    }
} 